package com.wj.ballcat.admin.filter;

import cn.hutool.core.util.ObjectUtil;
import com.hccake.ballcat.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.MimeHeaders;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @author WJ
 * 自定义过滤器
 */

@Slf4j
public class CustomHeaderFilter extends OncePerRequestFilter {


	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//		System.out.println("112233" + SecurityUtils.getUser());
//		String requestMethod = request.getMethod();
//		String token = request.getHeader("Authorization");
//		// options 直接放行
//		if (requestMethod.equals(HttpMethod.OPTIONS.name())) {
//			filterChain.doFilter(request, response);
//		}
//		if (!StringUtils.isEmpty(token)) {
//			// TODO 处理token调用addHeader方法
//			reflectSetHeader(request, "user-id", String.valueOf(SecurityUtils.getUser().getUserId()));
//			reflectSetHeader(request, "user-name", SecurityUtils.getUser().getUsername());
//		}
		filterChain.doFilter(request, response);
	}

	private void reflectSetHeader(HttpServletRequest request, String key, String value) {
		Class<? extends HttpServletRequest> requestClass = request.getClass();
		try {
			Field requestField = requestClass.getDeclaredField("request");
			requestField.setAccessible(true);
			Object requestObj = requestField.get(request);
			Field coyoteRequestField = requestObj.getClass().getDeclaredField("coyoteRequest");
			coyoteRequestField.setAccessible(true);
			Object coyoteRequestObj = coyoteRequestField.get(requestObj);
			Field headersField = coyoteRequestObj.getClass().getDeclaredField("headers");
			headersField.setAccessible(true);
			MimeHeaders headersObj = (MimeHeaders) headersField.get(coyoteRequestObj);
			headersObj.removeHeader(key);
			headersObj.addValue(key).setString(value);
		} catch (Exception e) {
			logger.error("reflect set header {} error {}");
		}
	}


}
